<?php
ob_start();
?>
<html>

<head>
	<link href="inc/style.css" rel="stylesheet" type="text/css" />
	<title>
		Login
	</title>
</head>

<body>
	<?php
		session_start();
		if(isset($_SESSION['user']))
		{
			header('Location: index.php');
		}
		else
		{
			$css = "hidden";
			if($_SERVER['REQUEST_METHOD'] == 'POST')
			{
				include('inc/functions.php');
				include('inc/config.php');
				if(connectBD($ip, $userdb, $passworddb, $db))
				{
					$user = mysql_real_escape_string(trim(strip_tags($_POST['username'])));
					$password = md5($_POST['password']);
					if(login($user, $password))
					{
						$query = ("SELECT Groups.Name FROM Groups inner join Users on Groups.GroupID = Users.GroupID WHERE Users.Name='$user'");
						$result = mysql_query($query);
						$row = mysql_fetch_row(($result));
						$group = $row[0];
						//inicio de sesión con el usuario y el grupo al que pertenece
						$_SESSION['user'] = $user;
						$_SESSION['group'] = $group;
						if ($group == "Teacher")
						{
							$_SESSION['validate'] = 0; //si es teacher valdra 0.
							header('Location: randonm.php'); // nos llevara a randonm
						}
						else
						{
							$_SESSION['validate'] = 1; //si no es teacher, sera 1.
							header('Location: index.php');
						}
						die();
					}
					else
					{
						$css = "visible"; //div de login incorrecto
					}
				}
				else
				{
					echo "Error!"; //conexión fallida con la db
				}
			}
		}
	?>
	<form action="" method="post" name="formLogin" class="formLogin">
		<div id='logoff' style='visibility:<?php echo $css; ?>'><center>Login failed!</center></div>
		<fieldset>
			<legend>Project Marks</legend>
			<p>
				<label for="username">Username: </label>
				<input type="text" id="username" name="username" tabindex="1" value="" title="username" />
			</p>
			<p>
				<label for="password">Password:</label>
				<input type="password" id="password" name="password" tabindex="2" title="password" />
			</p>
			<p>
				<input type="submit" value="Login" id="submit" class="button" tabindex="3" />
			</p>
		</fieldset>
	</form>
</body>

</html>
<?php
ob_end_flush();
?>